package com.ecric.http.socket;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.TextView;

import com.ecric.http.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ServerSocketActivity extends AppCompatActivity {


    TextView txt_serverSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_socket);
        txt_serverSocket = (TextView) findViewById(R.id.txt_serverSocket);
        txt_serverSocket.findViewById(R.id.txt_serverSocket);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //建立连接到远程服务器的socket
                    Socket socket = new Socket("192.168.11.139",30000);
                    //=================或者==============
                    //创建Socket对象
                    Socket s = new Socket();
                    //连接远程服务
                    s.connect(new InetSocketAddress("192.168.11.139",30000));
                    //设置超时时间
                    socket.setSoTimeout(10000);
                    BufferedReader bufferedReader  = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    //进行I／O 操作
                    final String result = bufferedReader.readLine();
                    if (!TextUtils.isEmpty(result)){
                        ServerSocketActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txt_serverSocket.setText(result);
                            }
                        });
                    }

                    //读取数据
//                    Scanner scanner = new Scanner(socket.getInputStream());
//                    StringBuffer  buffer = new StringBuffer();
//                    while (scanner.hasNext()){
//                        buffer.append(scanner.next());
//                    }
//                    scanner.close();

                    //关闭输入流、socket
                    bufferedReader.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
